package com.itheima.dao.impl;

import com.itheima.dao.AccountDao;
import com.itheima.po.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * ClassName:AccountDaoImpl
 * Package:com.itheima.dao.impl
 * Description:用户数据接口层实现类
 * QreryRunner类(org.apache.commons.dbutils.QueryRunner)
 * 是Dbutils的核心类之一，它显著的简化了SQL查询
 * <p>
 * Date:2020/2/21 15:44
 * User: snow
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
	@Resource
	private QueryRunner runner;


	public List<Account> findAllAccount() {
		try {
			return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public Account findAccountById(Integer id) {
		try {
			return runner.query("select * from account where id = ?", new BeanHandler<Account>(Account.class), id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void saveAccount(Account account) {
		try {
			runner.update("insert into account(name,money) values(?,?)", account.getName(), account.getMoney());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void updateAccount(Account account) {
		try {
			runner.update("update account set name = ? ,money = ? where id = ?", account.getName(), account.getMoney(), account.getId());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void deleteAccount(Integer id) {
		try {
			runner.update("delete from account  where id = ?", id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
